package com.easypay.reactive8583.netty.pipeline;

import com.solab.iso8583.IsoMessage;
import com.solab.iso8583.IsoValue;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.logging.LogLevel;
import io.netty.handler.logging.LoggingHandler;

import java.io.IOException;
import java.io.InputStream;
import java.util.Arrays;
import java.util.List;
import java.util.Properties;

/**
 * @author pandans
 * @date 2021/03/04 17:03
 * @Description:
 */
public class IsoMessageLoggingHandler extends LoggingHandler {
    private static final char MASK_CHAR = '*';
    private static char[] MASKED_VALUE = "***".toCharArray();

    public static List<Integer> DEFAULT_MASKED_FIELDS = Arrays.asList(
            34, // PAN extended
            35, // track 2
            36, // track 3
            45 // track 1
    );

    private static String[] FIELD_NAMES = new String[256];
    private static String FIELD_PROPERTIES = "iso8583fields.properties";

    private LogLevel level;
    private Boolean printSensitiveData;
    private Boolean printFieldDescriptions;
    private List<Integer> maskedFields = DEFAULT_MASKED_FIELDS;

    public IsoMessageLoggingHandler(LogLevel level) {
        super(level);
        this.level = level;
        loadProperties();
    }

    public IsoMessageLoggingHandler(LogLevel level, Boolean printSensitiveData, Boolean printFieldDescriptions, List<Integer> maskedFields) {
        super(level);
        this.level = level;
        this.printSensitiveData = printSensitiveData;
        this.printFieldDescriptions = printFieldDescriptions;
        if(maskedFields != null) {
            this.maskedFields = maskedFields;
        }
        loadProperties();
    }

    private void loadProperties() {
        try (InputStream stream = getPropertiesStream()) {
            Properties properties = new Properties();
            properties.load(stream);
            properties.forEach((key, value) -> {
                int field = Integer.parseInt(key.toString());
                FIELD_NAMES[field - 1] = String.valueOf(value);
            });
        } catch (IOException e) {
            throw new IllegalStateException("Unable to load ISO8583 field descriptions", e);
        } catch (NumberFormatException e) {
            throw new IllegalStateException("nable to load ISO8583 field descriptions", e);
        }
    }

    private InputStream getPropertiesStream(){
        InputStream stream =
                Thread.currentThread().getContextClassLoader()
                        .getResourceAsStream("/"+FIELD_PROPERTIES);
        if (stream == null) {
            stream = IsoMessageLoggingHandler.class.getResourceAsStream(
                    "/"+FIELD_PROPERTIES
            );
        }
        return stream;
    }

    @Override
    public String format(ChannelHandlerContext ctx, String eventName, Object arg) {
        if(arg instanceof IsoMessage) {
            return super.format(ctx, eventName, formatIsoMessage((IsoMessage) arg));
        }else {
            return super.format(ctx, eventName, arg);
        }
    }

    private String formatIsoMessage(IsoMessage m) {
        StringBuilder sb = new StringBuilder();
        if (printSensitiveData) {
            sb.append("Message: ").append(m.debugString()).append("\n");
        }
        sb.append("MTI: 0x").append(String.format("%04x", m.getType()));
        for (int i = 2; i < 128; i++) {
            if (m.hasField(i)) {
                IsoValue field = m.getField(i);
                sb.append("\n  ").append(i).append(": [");
                if (printFieldDescriptions) {
                    sb.append(FIELD_NAMES[i - 1]).append(':');
                }
                char[] formattedValue = getFormattedValue(field, i);
                sb.append(field.getType()).append('(').append(field.getLength())
                        .append(")] = '").append(formattedValue).append('\'');
            }
        }
        return sb.toString();
    }

    private char[] getFormattedValue(IsoValue field, int i){
        if(printSensitiveData) {
            return field.toString().toCharArray();
        }else {
            if(i == 2) {
                return maskPAN(field.toString());
            }else if(maskedFields.contains(i)) {
                return MASKED_VALUE;
            }else {
                return field.toString().toCharArray();
            }
        }
    }

    private char[] maskPAN(String fullPan) {
        char[] maskedPan = fullPan.toCharArray();
        for(int i = 6; i < maskedPan.length - 4; i++) {
            maskedPan[i] = MASK_CHAR;
        }
        return maskedPan;
    }

}
